import PubSub from 'pubsub-js';
import moment from 'moment'
import request from '../../../../utils/request'
// 获取全局实例
const appInstance = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isPlay: false, // 音乐是否播放
    playorder: '',  //控制播放顺序 icon-xunhuanbofang:循环播放 icon-suijibofang_ ：随机播放 icon-danquxunhuan1 ：单曲循环
    listHide: false,  //播放列表隐藏
    song: {}, // 歌曲详情对象
    musicId: '', // 音乐id
    musicLink: '', // 音乐的链接
    currentTime: '00:00',  // 实时时间
    durationTime: '00:00', // 总时长
    currentWidth: 0, // 实时进度条的宽度
    type:'',          //通信id
    shoucang:false     //收藏
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    let type = options.type;
    let musicId = options.musicId;
    let playorder = appInstance.globalData.playorder 
    this.setData({
      musicId,
      type,
      playorder
    })



    // 获取音乐详情
    this.getMusicInfo(musicId);
    if(appInstance.globalData.isMusicPlay && appInstance.globalData.musicId === musicId){ 
      // 修改当前页面音乐播放状态为true
      this.setData({
        isPlay: true
      })
    }
    // 监视音乐播放/暂停/停止
    appInstance.globalData.backgroundAudioManager.onPlay(() => {
      this.changePlayState(true);
      // console.log("播放")
      // 修改全局音乐播放的状态
      appInstance.globalData.musicId = musicId;
    });
    appInstance.globalData.backgroundAudioManager.onPause(() => {
      // console.log("暂停")
      this.changePlayState(false);
    });
    appInstance.globalData.backgroundAudioManager.onStop(() => {
      
      this.changePlayState(false);
    });
    
    // 监听音乐播放自然结束
    appInstance.globalData.backgroundAudioManager.onEnded(() => {
      let {playorder} = this.data
      switch(playorder) {
        case 'icon-danquxunhuan1':
           break;
        case 'icon-suijibofang_':
          appInstance.globalData.currentIndex = Math.round(Math.random()*appInstance.globalData.playList.length);
          break;
        default:     
          if(appInstance.globalData.currentIndex === appInstance.globalData.playList.length - 1){
            appInstance.globalData.currentIndex = -1;
          }
          appInstance.globalData.currentIndex++;
   } 


      // console.log("播放结束")
      // 自动切换至下一首音乐，并且自动播放
      PubSub.publish(this.data.type, 'next')
      // 将实时进度条的长度还原成 0；时间还原成 0；
      this.setData({
        currentWidth: 0,
        currentTime: '00:00'
      })
      this.flashurl();
    });
    
    // 监听音乐实时播放的进度
    appInstance.globalData.backgroundAudioManager.onTimeUpdate(() => {
      // console.log('总时长: ', appInstance.globalData.backgroundAudioManager.duration);
      // console.log('实时的时长: ', appInstance.globalData.backgroundAudioManager.currentTime);
      // 格式化实时的播放时间
      let currentTime = moment(appInstance.globalData.backgroundAudioManager.currentTime * 1000).format('mm:ss')
      let currentWidth = appInstance.globalData.backgroundAudioManager.currentTime/appInstance.globalData.backgroundAudioManager.duration * 450;
      this.setData({
        currentTime,
        currentWidth
      })
      
    })
     

    
  },





  // 修改播放状态的功能函数
  changePlayState(isPlay){
    // 修改音乐是否的状态
    this.setData({
      isPlay
    })
  
    // 修改全局音乐播放的状态
    appInstance.globalData.isMusicPlay = isPlay;
  },








  // 获取音乐详情的功能函数
  async getMusicInfo(musicId){
    // console.log(musicId)
    let songData = await request('/song/detail', {ids: musicId});
    // console.log(songData)
    // songData.songs[0].dt 单位ms
    let durationTime = moment(songData.songs[0].dt).format('mm:ss');
    this.setData({
      song: songData.songs[0],
      durationTime
    })
    
    
    // 动态修改窗口标题
    wx.setNavigationBarTitle({
      title: this.data.song.name
    })

    //播放音乐
   
    this.getMusicUrl(musicId)
    appInstance.globalData.songData = songData

  },








  // 点击播放/暂停的回调
  handleMusicPlay(){
    let isPlay = !this.data.isPlay;
    
    let {musicId, musicLink} = this.data;
    this.musicControl(isPlay, musicId, musicLink);
  },
  





  // 控制音乐播放/暂停的功能函数
   musicControl(isPlay, musicId, musicLink){
    
    if(isPlay){ // 音乐播放
      appInstance.globalData.backgroundAudioManager.play();
    }else { // 暂停音乐
      appInstance.globalData.backgroundAudioManager.pause();
    }
    
  },


  // 获取音乐url
 async getMusicUrl(musicId){
   
   let {musicLink} = this.data
  
    // 获取音乐播放链接
    let musicLinkData = await request('/song/url', {id: musicId});

    musicLink = musicLinkData.data[0].url;
    
    this.setData({
      musicLink
    })
     this.flag = true;
    // 返回url为空 自动播放下一首
    if(!this.data.musicLink &&  this.flag === true){
      this.flag = false;
     
        wx.showToast({
          title: '该单曲已下架!',
          duration: 2000,
          image:'/static/images/sorry.png',
          success:()=>{
          }

        })

        if(appInstance.globalData.currentIndex === appInstance.globalData.playList.length - 1){
          appInstance.globalData.currentIndex = -1;
        }
        appInstance.globalData.currentIndex++;
        PubSub.publish(this.data.type, 'next')
        // 将实时进度条的长度还原成 0；时间还原成 0；
        this.setData({
          currentWidth: 0,
          currentTime: '00:00'
        })
        this.flashurl();
      return 
      }
      wx.removeStorageSync({
        key: 'songInfo',
      })
      wx.setStorageSync(
        'songInfo',
         JSON.stringify({
          id:this.data.song.id,
          type:this.data.type,
          songname:this.data.song.al.name,
          arname:this.data.song.ar[0].name,
          picurl:this.data.song.al.picUrl,
          musicLink:this.data.musicLink
        }),
  
      )
      
      appInstance.globalData.songInfo = {
        id:this.data.song.id,
        type:this.data.type,
        songname:this.data.song.al.name,
        arname:this.data.song.ar[0].name,
        picurl:this.data.song.al.picUrl,
        musicLink:this.data.musicLink
      }
      // console.log(appInstance.globalData.songInfo)
      

  appInstance.globalData.backgroundAudioManager.src = musicLink;
  appInstance.globalData.backgroundAudioManager.title = this.data.song.name;
 },



  
  // 点击切歌的回调
  handleSwitch(event){
    let {playorder} = this.data
    // 获取切歌的类型
    let type = event.currentTarget.id;
    // console.log(type)
    if(playorder==='icon-suijibofang_'){
      appInstance.globalData.currentIndex = Math.round(Math.random()*appInstance.globalData.playList.length);
      // console.log(appInstance.globalData.currentIndex)
    }else{
      if(type === "next"){
        if(appInstance.globalData.currentIndex === appInstance.globalData.playList.length - 1){
          appInstance.globalData.currentIndex = -1;
        }
        appInstance.globalData.currentIndex++;
      }else{
        if(appInstance.globalData.currentIndex === 0){
          appInstance.globalData.currentIndex = appInstance.globalData.playList.length 
        }
        appInstance.globalData.currentIndex--;
      }
    }


    // 关闭当前播放的音乐
    appInstance.globalData.backgroundAudioManager.stop();
    // 发布消息数据给recommendSong页面
    console.log(appInstance.globalData.currentIndex)
    
    PubSub.publish(this.data.type, type)
    //刷新url
    this.flashurl();
  },


  //封装数据之间的通信-刷新url
  flashurl(){
        // // 订阅来自recommendSong页面发布的musicId消息
        PubSub.subscribe('musicId', (msg, musicId) => {
         
          // 获取音乐详情信息
          this.getMusicInfo(musicId);
          //获取音乐url
          this.getMusicUrl(musicId);
          // 自动播放当前的音乐
          this.musicControl(true, musicId,this.data.musicLink);
          // 取消订阅
          PubSub.unsubscribe('musicId');
        })
        
  },

  //显示播放列表
  playlistshow(){
    let listHide = !this.data.listHide
    this.setData({
      listHide
    })
  },
  //隐藏播放列表
  playlisthide(){

    let listHide = !this.data.listHide
    if(!listHide === false)return
    else{
      this.setData({
        listHide
      })
    }
  },


  //点击音乐列表
  changePlay(event) {
    // console.log(event.detail.musicId)
    let musicid = event.detail.musicId
    let musicindex = event.detail.musicindex
    appInstance.globalData.currentIndex = musicindex
    this.getMusicInfo(musicid)
    if(appInstance.globalData.isMusicPlay && appInstance.globalData.musicId === musicid){ 
      // 修改当前页面音乐播放状态为true
      this.setData({
        isPlay: true,
      })
    }
    this.setData({
      listHide: false
    })
  },

  //切换播放顺序
  handleSwitchplayorder(){
    let {playorder} = this.data
    
    switch(playorder) {
      case 'icon-xunhuanbofang':
         playorder = 'icon-suijibofang_';
         appInstance.globalData.playorder = playorder
         break;
      case 'icon-suijibofang_':
        playorder = 'icon-danquxunhuan1';
        appInstance.globalData.playorder = playorder;
         break;
      case 'icon-danquxunhuan1':
         playorder = 'icon-xunhuanbofang';
         appInstance.globalData.playorder = playorder;
          break;
    } 
    this.setData({
      playorder
    })
  },




//抽屉
showModal(e) {
  this.setData({
    modalName: e.currentTarget.dataset.target
  })
},
hideModal(e) {
  this.setData({
    modalName: null
  })
},
async shoucang(){
  let {shoucang,musicId} = this.data
  if(!shoucang){
    let res = await request('/song/url', {id: musicId});
    // console.log(res)
  }else{
    let res = await request('/song/url', {id: musicId,like:false});
    console.log(res)
  }
  shoucang = !shoucang
  this.setData({
    shoucang
  })
},



































  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
